import React, { useState, useRef, useEffect } from "react";
import {
  NavBar,
  Button,
  Modal,
  Tabs,
  Toast,
  Avatar,
  Card,
  TextArea,
} from "antd-mobile";
import constant from "./common/Constants";
import util from "./common/Util";
import { useNavigate } from "react-router-dom";
import "./css/MXChat.scss";
import { CloseCircleOutline, AddOutline } from "antd-mobile-icons";
/**
 * minimax对话
 */
function MXChat() {
  const navigate = useNavigate();
  const back = () => {
    navigate("/menuList");
  };
  const uuid = util.guid();
  const tabCountRef = useRef(1);
  const textRef = useRef(null);
  const innerContentRef = useRef(null);
  const updateSource = useRef("");
  const [activeKey, setActiveKey] = useState(uuid);
  const [tabConfig, setTabConfig] = useState({
    [uuid]: {
      title: "对话1",
      key: uuid,
      itemList: [],
    },
  });
  const addTab = (e) => {
   
    const uuid = util.guid();
    tabCountRef.current++;

    tabConfig[uuid] = {
      title: "对话" + tabCountRef.current,
      key: uuid,
      sessionId: uuid,
      itemList: [],
    };
    setTabConfig({ ...tabConfig });
    setActiveKey(uuid);

    e.stopPropagation();
  };
  const closeTab = (key, event) => {
    let keys = Object.keys(tabConfig);
    if (keys.length == 1) {
      return;
    }
    delete tabConfig[key];
    keys = Object.keys(tabConfig);
    updateSource.current = "";
    setTabConfig({ ...tabConfig });
    setActiveKey(keys[keys.length - 1]);
    event.stopPropagation();
    return false;
  };

  const changeTab = (e) => {
    setActiveKey(e);
    console.info("切换tab,当前:" + e);
  };
  const send = () => {
    let val = textRef.current.nativeElement.value;
    if (val) {
      let url =
        constant.baseUrl + "/app/chatCompletionPro?token=" + util.getToken();
      const tab = tabConfig[activeKey];
      if (textRef.current) {
        textRef.current.clear();
      }
      const item = {
        sender_type: "USER",
        sender_name: "我",
        text: val,
      };
      updateSource.current = "send";
      let itemList = [...tab.itemList, item];
      tab.itemList = itemList;
      setTabConfig({ ...tabConfig });

      util.postJson(url, { sessionMessages: tab.itemList }, (ret) => {
        console.info("回应", ret);
        if (ret.code === 0) {
          const reply = ret.reply;
        
          tab.itemList = [...tab.itemList, ret.replyMessage];
          setTabConfig({ ...tabConfig });
        } else {
          Toast.show({
            content: "信息:" + ret.message,
            position: "top",
          });
        }
      });
    }
  };

  useEffect(() => {
    if (updateSource.current === "send") {
      if (innerContentRef.current) {
        innerContentRef.current.scrollTop =
          innerContentRef.current.scrollHeight;
      }
    }
  }, [tabConfig]);

  return (
    <div className="MXChat2 container">
      <div className="main">
        <div className="nav">
          <NavBar onBack={back} style={{ "--border-bottom": "1px #eee solid" }}>
            米麦对话
          </NavBar>
        </div>
        <div className="content">
          <Tabs
            stretch={false}
            activeKey={activeKey}
            className="tabs"
            onChange={changeTab}
            style={{ "--content-padding": "10px" }}
          >
            {Object.keys(tabConfig).map((key) => {
              let tab = tabConfig[key];

              return (
                <Tabs.Tab
                  title={
                    <div>
                      {tab.title}
                      <span
                        onClick={closeTab.bind(this, tab.key)}
                        style={{ paddingLeft: "10px", display: "inline-block" }}
                      >
                        <CloseCircleOutline fontSize={18} />
                      </span>
                    </div>
                  }
                  key={tab.key}
                  className="tab"
                >
                  <div className="inner-content" ref={innerContentRef}>
                    {tab.itemList.length === 0 && (
                      <div>{tab.title}提交内容开启对话</div>
                    )}

                    {tab.itemList.map((item, index) => {
                      return (
                        <MxChatItem
                          item={item}
                          key={tab.key + "-" + index}
                        ></MxChatItem>
                      );
                    })}
                  </div>
                </Tabs.Tab>
              );
            })}

            <Tabs.Tab
              title={<AddOutline onClick={addTab} />}
              key={"addBtn"}
            ></Tabs.Tab>
          </Tabs>
        </div>
        <div className="footer">
          <div className="footer-left">
            <TextArea
              style={{ "--font-size": "16px" }}
              rows={1}
              autoSize={true}
              placeholder={"请输入内容"}
              ref={textRef}
            ></TextArea>
          </div>
          <div className="footer-right">
            <Button
              // style={{'--background-color':'#57be6b','--border-color':'#57be6b'}}
              className="button"
              size="small"
              color="primary"
              onClick={send}
            >
              发送
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

/**
 * 对话列表
 * @param {} props
 * @returns
 */
function MxChatItem(props) {
  const demoAvatarImages = [
    "https://pic.rmb.bdstatic.com/bjh/news/ab71d7a4aa2ddb880fd01d3ffc165dc3.jpeg",
    "https://img1.baidu.com/it/u=1972540820,1438806685&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
    "https://images.unsplash.com/photo-1542624937-8d1e9f53c1b9?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ",
    "https://images.unsplash.com/photo-1546967191-fdfb13ed6b1e?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ",
  ];

  let { sender_type, sender_name, text } = props.item;

  if (sender_type === "BOT") {
    return (
      <div className="chat-row left">
        <div className="chat-head">
          <Avatar
            className="chat-avatar"
            src={demoAvatarImages[0]}
            style={{ "--size": "42px", "--border-radius": "8px" }}
          />
        </div>
        <div className="chat-content">
          <span className="chat-name">{sender_name}</span>
          <Card className="chat-card">{text}</Card>
        </div>
        <div className="chat-space"></div>
      </div>
    );
  } else if (sender_type === "USER") {
    return (
      <div className="chat-row right">
        <div className="chat-head">
          <Avatar
            className="chat-avatar"
            src={demoAvatarImages[1]}
            style={{ "--size": "42px", "--border-radius": "8px" }}
          />
        </div>
        <div className="chat-content">
          <span className="chat-name">{"我"}</span>
          <Card className="chat-card">{text}</Card>
        </div>
        <div className="chat-space"></div>
      </div>
    );
  }
  return "";
}

export default MXChat;
